package com.example.springbootvuedemo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.springbootvuedemo.domain.Book;
import com.example.springbootvuedemo.mapper.BookMapper;
import com.example.springbootvuedemo.service.BookService;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

@Service
public class BookServiceImpl implements BookService {
    @Autowired
    private BookMapper bookMapper;
    @Override
    public Boolean save(Book book) throws IOException {
        //手动抛出异常，测试异常捕获
        if(book.getName().equals("123")){
            throw new IOException();
        }
        return bookMapper.insert(book) > 0;
    }

    @Override
    public Boolean update(Book book) {
        return bookMapper.updateById(book) > 0;
    }

    @Override
    public Boolean delete(Integer id) {
        return bookMapper.deleteById(id) > 0;
    }

    @Override
    public Book getById(Integer id) {
        return bookMapper.selectById(id);
    }

    @Override
    public List<Book> getAll() {
        return bookMapper.selectList(null);
    }

    @Override
    public IPage<Book> getByPage(Integer current, Integer size) {
        IPage page=new Page(current,size);
        return bookMapper.selectPage(page, null);
    }

    @Override
    public IPage<Book> getByPageSelect(Integer current, Integer size, Book book) {
        IPage page=new Page(current,size);
        LambdaQueryWrapper<Book> lqw=new LambdaQueryWrapper<Book>();
        lqw.like(Strings.isNotEmpty(book.getName()),Book::getName,book.getName());
        lqw.like(Strings.isNotEmpty(book.getAuthor()),Book::getAuthor,book.getAuthor());
        lqw.like(book.getPrice()!=null,Book::getPrice,book.getPrice());
        return bookMapper.selectPage(page, lqw);
    }
}
